package ai.hou.camera.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author zhaoxiaolei
 * @date 2021/3/18 16:27
 */
public class ScanTipView extends View {

    private final Paint mPaint;
    private final List<Point> points = new ArrayList<>();
    private final Random random;

    public ScanTipView(Context context) {
        this(context, null);
    }

    public ScanTipView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ScanTipView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(Color.GREEN);
        mPaint.setStyle(Paint.Style.FILL);
        random = new Random();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        for (int i = 0; i < 100; i++) {
            int x = w / 4 + random.nextInt(w / 2);
            int y = h / 4 + random.nextInt(h / 4);
            Point point = new Point(x, y);
            points.add(point);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (isScanning) {
            int count = random.nextInt(10);
            for (int i = 0; i < count; i++) {
                int index = random.nextInt(100);
                Point point = points.get(index);
                Log.d("TAG", "onDraw: "+point.toString());
                canvas.drawCircle(point.x, point.y, random.nextFloat() * 6, mPaint);
            }
        }
    }

    private boolean isScanning;
    private final Runnable scanRunnable = () -> {
        invalidate();
        startScanTip();
    };

    public void startScanTip() {
        isScanning = true;
        postDelayed(scanRunnable, 100);
    }

    public void stopScanTip() {
        isScanning = false;
        invalidate();
        removeCallbacks(scanRunnable);
    }
}
